'''
Created on 31/10/2009

@author: kuryaki
'''
import urllib
import simplejson

TEMPLATE = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0"

def search_url(word):
    url = TEMPLATE
    url += "&q=" + urllib.quote(word)
    url += "&as_filetype=jpg&imgsz=small"
    return url

def search(word):
    f=urllib.urlopen(search_url(word))
    ret=simplejson.load(f)
    return ret['responseData']['results'][0]['unescapedUrl']

def toBase64(url):
    import base64
    img = urllib.urlopen(url)
    encoded = base64.b64encode(img.read())
    return encoded


if __name__=='__main__':
  import sys
  from pprint import pprint
  if len(sys.argv) > 1:
    q = " ".join(sys.argv[1:])
  else: q = "query a question to whom in what sense"
  url = search(q)
  pprint(toBase64(url))

